package cn.tedu.charging.order.emqx;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MqttProducer<T> {
    private final MqttClient mqttClient;
    private final MySerializer<T> mySerializer;

    @Autowired
    public MqttProducer(MqttClient mqttClient, MySerializer<T> mySerializer) {
        this.mqttClient = mqttClient;
        this.mySerializer = mySerializer;
    }
    /**
     * 发送消息
     * String topic: 主题
     * T message: 消息体
     * qos: 服务质量
     * boolean retained: 是否保留消息
     */
    public boolean sendMessage(String topic, T message, int qos, boolean retained) {
        try {
            mqttClient.publish(topic, mySerializer.serialize(message), qos, retained);
        } catch (Exception e) {
            log.error("消息发送失败", e);
        }
        return true;
    }

    // 发送,利用至少一次,存储消息
    public boolean sendAtLeastOnceStored(String topic, T message) {
        return this.sendMessage(topic, message, 1, true);
    }
}
